//
//  DateAlertController.swift
//  SwiftDemo2
//
//  Created by ShareAnimation on 2017/10/10.
//  Copyright © 2017年 爱丽丝的梦境. All rights reserved.
//

import UIKit

class DateAlertController: UIViewController {
    
    var coverView: UIView = {
        let view = UIView()
        view.backgroundColor = UIColor.black.withAlphaComponent(0.3)
        return view
    }()
    
    var panel: UIView = {
        let view = UIView()
        view.backgroundColor = UIColor.white
        view.layer.cornerRadius = 12
        view.layer.masksToBounds = true
        
        return view
    }()
    
    lazy var pickerView: UIPickerView = {
        let pickerview = UIPickerView()
        pickerview.delegate = self
        pickerview.dataSource = self
        return pickerview
    }()
    
    var toolBar: UIToolbar = {
        let toolBar = UIToolbar()
        
        let cancelButton = UIBarButtonItem(title: "取消", style: .done, target: self, action: #selector(doCancelAction))
        let flexibleSpace = UIBarButtonItem(barButtonSystemItem: .flexibleSpace, target: nil, action: nil)
        let okButton = UIBarButtonItem(title: "确认", style: .done, target: self, action: #selector(doOkAciton))
        toolBar.items = [cancelButton, flexibleSpace, okButton]
        
        return toolBar
    }()
    
    fileprivate var months: [Int] = {
        var arr = [Int]()
        for i in 1...12 {
            arr.append(i)
        }
        
        return arr
    }()
    
    fileprivate var years: [Int] = {
        var arr = [Int]()
        for i in 1990...2100 {
            arr.append(i)
        }
        
        return arr
    }()
    
    //选择器上显示的年月，默认是今天
    fileprivate var month: String?
    fileprivate var year: String?
    
    //选择器的显示的日期。
    //  get:根据变量month和year获取当前选择器显示的日期。set:会设置month和year的值，同时让选择器指向set的日期
    //  注意：年的范围在[1900,2100]
    var date: Date {
        get {
            if month != nil && year != nil {
                let monthAndYearString = year! + month!
                let formatter = DateFormatter()
                formatter.dateFormat = "yyyy年MM月"
                let date = formatter.date(from: monthAndYearString)!
                return date
            }
            return Date()
        }
        set {
            let monthFormatter = DateFormatter()
            let yearFormatter = DateFormatter()
            monthFormatter.dateFormat = "MM"
            yearFormatter.dateFormat = "yyyy"
            let monthString = monthFormatter.string(from: newValue)
            let yearString = yearFormatter.string(from: newValue)
            self.month = monthString + "月"
            self.year = yearString + "年"
            
            let monthIndex = self.months.index(of: Int(monthString)!)
            let yearIndex = self.years.index(of:  Int(yearString)!)
            self.pickerView.selectRow(monthIndex!, inComponent: 1, animated: true)
            self.pickerView.selectRow(yearIndex!, inComponent: 0, animated: true)
        }
    }
    
    init(_ handler: @escaping (Date) -> Void) {
        super.init(nibName: nil, bundle: nil)
        self.transitioningDelegate = self
        self.okHandler = handler

        self.date = Date()
    }
    
    required init?(coder aDecoder: NSCoder) {
        fatalError("init(coder:) has not been implemented")
    }
    
    var okHandler:((Date) -> Void)?

    override func viewDidLoad() {
        super.viewDidLoad()
        self.view.backgroundColor = UIColor.clear

        self.setupViews()
    }

    func setupViews() {
        let viewHeight = self.view.bounds.height
        let viewWidth = self.view.bounds.width
        
        self.view.addSubview(self.coverView)
        self.coverView.frame = self.view.frame
        
        self.coverView.addSubview(self.panel)
        self.panel.frame = CGRect(x: 20, y: viewHeight-400, width: viewWidth-40, height: 320)
        
        self.panel.addSubview(self.toolBar)
        self.toolBar.frame = CGRect(x: 0, y: 0, width: self.panel.bounds.width, height: 44)
        
        self.panel.addSubview(self.pickerView)
        self.pickerView.frame = CGRect(x: 0, y: 44, width: self.panel.bounds.width, height: self.panel.bounds.height - self.toolBar.bounds.height)
    }
    
    @objc func doCancelAction() {
        self.dismiss(animated: true, completion: nil)
    }
    
    @objc func doOkAciton() {
        if let handler = self.okHandler {
            handler(self.date)
            self.dismiss(animated: true, completion: nil)
        }
    }
}

//MARK:UIPickerViewDelegate
extension DateAlertController: UIPickerViewDelegate,UIPickerViewDataSource {
    func numberOfComponents(in pickerView: UIPickerView) -> Int {
        return 2
    }
    
    func pickerView(_ pickerView: UIPickerView, numberOfRowsInComponent component: Int) -> Int {
        return [self.years.count,self.months.count][component]
    }
    
    func pickerView(_ pickerView: UIPickerView, titleForRow row: Int, forComponent component: Int) -> String? {
        if component == 0 {
            return "\(self.years[row])" + "年"
        }
        else {
            return "\(self.months[row])" + "月"
        }
    }
    
    func pickerView(_ pickerView: UIPickerView, didSelectRow row: Int, inComponent component: Int) {
        if component == 0 {
            self.year = "\(self.years[row])" + "年"
        }
        if component == 1 {
            self.month = "\(self.months[row])" + "月"
        }
        
//        //选择的日期不能超过当前日期
//        let result = self.date.compare(Date())
//        if result == .orderedDescending {
//            self.date = Date()
//        }
    }
}


//MARK:TransitioningDelegate
extension DateAlertController: UIViewControllerTransitioningDelegate {
    func animationController(forPresented presented: UIViewController, presenting: UIViewController, source: UIViewController) -> UIViewControllerAnimatedTransitioning? {
        return DateAlertControllerTransionPresent()
    }
    
    func animationController(forDismissed dismissed: UIViewController) -> UIViewControllerAnimatedTransitioning? {
        return DateAlertControllerTransionDismiss()
    }
}

class DateAlertControllerTransionPresent:NSObject, UIViewControllerAnimatedTransitioning {
    func transitionDuration(using transitionContext: UIViewControllerContextTransitioning?) -> TimeInterval {
        return 0.4
    }
    
    func animateTransition(using transitionContext: UIViewControllerContextTransitioning) {
        let fromView = transitionContext.view(forKey: .from)
        let toVc = transitionContext.viewController(forKey: .to) as! DateAlertController
        let container = transitionContext.containerView
        container.addSubview(toVc.view)
        
        let panelView = toVc.panel
        let coverview = toVc.coverView
        coverview.backgroundColor = UIColor.black.withAlphaComponent(0.01)
        panelView.transform = CGAffineTransform.init(scaleX: 0.8, y: 0.8)
        UIView.animate(withDuration: 0.25, animations: {
             panelView.transform = CGAffineTransform.init(scaleX: 1.1, y: 1.1)
            coverview.backgroundColor = UIColor.black.withAlphaComponent(0.3)
        }) { (finish) in
            UIView.animate(withDuration: 0.05, animations: {
                panelView.transform = CGAffineTransform.identity
            })

            transitionContext.completeTransition(!transitionContext.transitionWasCancelled)
            toVc.view.addSubview(fromView!)
            toVc.view.sendSubview(toBack: fromView!)
        }
    }
}

class DateAlertControllerTransionDismiss:NSObject, UIViewControllerAnimatedTransitioning {
    func transitionDuration(using transitionContext: UIViewControllerContextTransitioning?) -> TimeInterval {
        return 0.4
    }
    
    func animateTransition(using transitionContext: UIViewControllerContextTransitioning) {
        
        let fromVc = transitionContext.viewController(forKey: .from) as! DateAlertController
        
        let panelView = fromVc.panel
        let coverview = fromVc.coverView
        UIView.animate(withDuration: 0.05, animations: { 
            panelView.transform = CGAffineTransform.init(scaleX: 1.1, y: 1.1)
        }) { (_) in
            UIView.animate(withDuration: 0.25, animations: { 
                panelView.transform = CGAffineTransform.init(scaleX: 0.1, y: 0.1)
                coverview.backgroundColor = UIColor.black.withAlphaComponent(0.01)
            }, completion: { (_) in
                transitionContext.completeTransition(!transitionContext.transitionWasCancelled)
            })
        }
    }
}

